<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>角色管理</title>
    <base href="/role/">
    <link rel="stylesheet" href="/webjars/layui/2.5.6/css/layui.css">
    <script src="/webjars/layui/2.5.6/layui.js" type="text/javascript"></script>
</head>
<body>

<script id="userTool" type="text/html">
    <button class="layui-btn" onclick="userAdd()">添加</button>
    <button class="layui-btn" onclick="batchDel()">批量删除</button>
</script>
<script id="userDCL" type="text/html">
    <button class="layui-btn" lay-event="userUpdate">修改</button>
</script>

<div>
    <table id="userTable" lay-filter="userTable" class="layui-table"></table>
</div>

<div id="userHandler" style="display: none">
    <form class="layui-form" id="userForm" lay-filter="userForm" style="padding: 35px;">
        <div class="layui-form-item">
            <label class="layui-form-label">角色编号</label>
            <div class="layui-input-inline">
                <input type="text" name="roleId" required  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色名称</label>
            <div class="layui-input-inline">
                <input type="text" name="roleName" required  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">可用|禁用</label>
            <div class="layui-input-block">
                <input name="available" type="checkbox" value="1" lay-skin="switch">
            </div>
        </div>
    </form>
</div>

<div id="permissionHandler" style="display: none">
    <form class="layui-form" id="permissionForm" lay-filter="permissionForm" style="padding: 35px;">
        <div class="layui-form-item" th:each="permission : ${permissions.entrySet()}">
            <input type="checkbox" th:title="${permission.getKey().name}" name="permissionId" th:value="${permission.getKey().id}" lay-filter="allPermission">
<!--            <label style="cursor: pointer" class="layui-form-label allPermission"  th:text="${permission.getKey().name}" lay-filter="allPermission">复选框</label>-->
            <div class="layui-input-block">
<!--                <input type="checkbox" th:title="${permission.getKey().name}" name="permissionId" th:value="${permission.getKey().id}">-->
                <input type="checkbox" name="permissionId" lay-filter="c_one" th:each="zi : ${permission.getValue()}" th:value="${zi.id}" th:title="${zi.name}" lay-skin="primary">
            </div>
        </div>
    </form>
</div>
<script type="text/html" id="titleTpl">
    {{#  if(d.available==1){ }}
    <div class="layui-form-item">
        <label class="layui-form-label">可用|禁用</label>
        <div class="layui-input-block" roleId="{{d.roleId}}">
            <input type="checkbox" lay-filter="switchTest" checked  value="1" lay-skin="switch">
        </div>
    </div>
    {{#  } else { }}
    <div class="layui-form-item">
        <label class="layui-form-label">可用|禁用</label>
        <div class="layui-input-block" roleId="{{d.roleId}}">
            <input type="checkbox" lay-filter="switchTest" value="1" lay-skin="switch">
        </div>
    </div>
    {{#  } }}
</script>
</body>
<script>
    function permissionId(roleId) {
        layui.use(['table', 'form', 'jquery', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var $ = layui.jquery;
            var layer = layui.layer;
            var ids=$("[name=permissionId]");
            var msg;
            $.ajax({
                type:"get",
                url:"permissionIds?roleId=00"+roleId,
                async:false,//设置同步/异步的参数[true异步  false同步]
                dataType:"text",
                success:function(data){
                    msg=data;
                },
                error:function(e){
                    msg=e;
                }
            });
            // $.get("permissionIds?roleId=00"+roleId,({msg})=>{
            //     console.log("ids:"+msg);
            //     var ids=msg.split(",");
            //
            // })
            console.log("ids:"+msg);
            var msgs=msg.split(",");
            $("[name=permissionId]").prop("checked",false);
            for (var z=0;z<msgs.length;z++){
                console.log("for:"+msgs[z])
                var zhi=msgs[z];
                $("[name=permissionId][value='"+msgs[z]+"']").prop('checked',true);
            }

            form.render('checkbox');
            layer.open({
                type: 1,
                title: "修改",
                area: ["500px","450px"],
                content: $("#permissionHandler"),
                btn: ['确定', '取消'],
                yes() {
                    var permiIds="";
                    $(ids).each(function () {
                        if(this.checked){
                            permiIds+=$(this).val()+",";
                        }
                    })
                    console.log("ids:"+permiIds)
                    $.post("updateRolePermission",{sysRoleId:"00"+roleId,sysPermissionId:permiIds}).done(({msg})=>{
                        layer.close(layer.index)
                        layer.msg(msg);
                        form.render('select');
                        table.reload("userTable")
                    })
                }
            })
        })
    }



    function userAdd() {
        userDCL("add");
    }
    function userUpdate(data) {
        userDCL("update",data);
        // console.log(data);
    }

    function userDCL(path,data) {
        layui.use(['table', 'form', 'jquery', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var $ = layui.jquery;
            var layer = layui.layer;
            var msg="修改"
            if(path=="add"){
                $("#userForm")[0].reset();
                msg="添加";
            }else {
                form.val("userForm",data);
            }
            layer.open({
                type: 1,
                title: msg,
                area: ["500px","450px"],
                content: $("#userHandler"),
                btn: ['确定', '取消'],
                yes() {
                    let user = form.val("userForm");
                    console.log(user)
                    $.post(path,user).done(({msg})=>{
                        layer.close(layer.index)
                        layer.msg(msg);
                        form.render('select');
                        table.reload("userTable")
                    })
                }
            })
            form.on("click(allPermission)",function (data) {
                layer.msg("触发了"+data)
            })
        })
    }
    function searchByUserName(){
        var $=layui.jquery;
        var status=$("#status").val();
        layui.table.reload('userTable',{where:{status:status}})
    }
    layui.use(['table','form','laydate','jquery','element','layedit'],function () {
        //创建一个编辑器

        let table=layui.table;
        let form=layui.form;
        let $=layui.jquery;
        let laydate=layui.laydate;
        let layedit=layui.layedit;
        table.render({
            id:"userTable",
            elem:"#userTable",
            url:"/role/list",
            toolbar:"#userTool",
            cols:[
                [
                    {type:"checkbox"},
                    {title:"角色编号  ",field:"roleId"},
                    {title:"角色名称  ",field:"roleName"},
                    {title:"角色状态", templet: '#titleTpl'},
                    {title:"权限",templet:`<div ><span roleId="{{d.roleId}}"  onclick="permissionId({{d.roleId}})">权限</span></div>`},
                    {title:"操作",toolbar: "#userDCL"}
                ]
            ],
            page:{
                limit:6,
                limits:[9,12,15]
            }
        });
        table.on("tool(userTable)",function ({data,event}) {
            switch (event) {
                case "userUpdate":
                    userUpdate(data);
            }
        })
        //监听指定开关
        form.on('switch(switchTest)', function (data) {
            var status=this.checked ? '1' : '0';
            var roleId=$(this).parent().attr("roleId");
            console.log(roleId+"编号:修改"+status)
            $.post("update",{roleId:roleId,available:status}).done(({msg})=>{
                layer.msg(msg);
            })


        });
        //全选
        form.on('checkbox(allPermission)', function (data) {
            var a = data.elem.checked;
            $(this).next().next().find("[name=permissionId]").prop("checked",a)
            form.render('checkbox');
        });
        form.on('checkbox(c_one)', function (data) {
            var item = $(this).parent().find("[name=permissionId]");
            for (var i = 0; i < item.length; i++) {
                if (item[i].checked == true) {
                    $(this).parent().prev().prev().prop("checked", true);
                    break;
                }else{
                    $(this).parent().prev().prev().prop("checked", false);

                }
            }
            form.render('checkbox');
            // //如果都勾选了  勾上全选
            // var  all=item.length;
            // for (var i = 0; i < item.length; i++) {
            //     if (item[i].checked == true) {
            //         all--;
            //     }
            // }
            // if(all==0){
            //     $("#c_all").prop("checked", true);
            //     form.render('checkbox');}
        });


    })
    //批量删除
    function batchDel() {
        layui.use(['table','layer','jquery'],function () {
            var table=layui.table;
            var layer=layui.layer;
            var $=layui.jquery;
            var product=table.checkStatus("userTable").data;
            var ids=product.map(product=>"ids="+product.roleId).join("&")
            if(ids==""){
                layer.msg("请选择要删除的角色")
                return;
            }
            console.log(product)
            console.log(ids)
            $.get("patchDel?"+ids,({msg})=>{
                layer.msg(msg)
                table.reload("userTable");
            })

        })
    }
</script>
</body>
</html>